package com.augrain.microframework.trace.instrument.client;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.core.Ordered;
import org.springframework.core.PriorityOrdered;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * RestTemplate后置处理器
 *
 * @author biaoy
 * @since 2021/08/22
 */
public class RestTemplatePostProcessor implements BeanPostProcessor, PriorityOrdered {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof RestTemplateBuilder) {
            RestTemplate restTemplate = ((RestTemplateBuilder) bean).build();
            process(restTemplate);
        }

        if (bean instanceof RestTemplate) {
            process((RestTemplate) bean);
        }
        return bean;
    }

    private void process(RestTemplate restTemplate) {
        List<ClientHttpRequestInterceptor> interceptors = restTemplate.getInterceptors();
        interceptors.add(new TraceClientHttpRequestInterceptor());
        restTemplate.setInterceptors(interceptors);
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE + 1;
    }
}
